package com.my.ruyi.ssl;

import java.nio.charset.Charset;

import javax.net.ssl.SSLEngine;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;

public class SslClientInitializer extends ChannelInitializer<SocketChannel>{

	private final SslContext context;
	
	public SslClientInitializer(SslContext sslContext) {
		this.context = sslContext;
	}
	
	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		System.out.println("SslClientInitializer-initChannel");
		ChannelPipeline pipeline = ch.pipeline();
		
		SSLEngine engine = context.newEngine(ch.alloc());
		// 客户端模式
		engine.setUseClientMode(true);
		// 首先添加SSL处理程序以加密和解密所有内容。
		// 1. 第一种方式
		//pipeline.addLast(context.newHandler(ch.alloc(), SslClient.HOST, SslClient.PORT));
		
		// 2. 第二种方式
		pipeline.addFirst("ssl", new SslHandler(engine));
		
		pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
		pipeline.addLast(new StringDecoder(Charset.forName("UTF-8")));
		pipeline.addLast(new StringEncoder(Charset.forName("UTF-8")));
		
		// 添加自己的业务处理逻辑
		pipeline.addLast(new SslClientHandler());
	}

}
